package com.ld.controller;

import com.ld.common.R;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {

    @RequestMapping(value = "upload" ,method = RequestMethod.POST)
    public R upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        multipartFile.getOriginalFilename();
        try {
            String path = request.getServletContext().getRealPath("/"); //也可以自定义路径
            System.out.println(path);
//            multipartFile.getName()获取到的是RequestParam中设置的值，multipartFile.getOriginalFilename()获取的是真实的文件名字
            File targetFile = new File(path,multipartFile.getOriginalFilename());
            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            multipartFile.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @RequestMapping(value = "download" ,method = RequestMethod.GET)
    public void download(@RequestParam(name = "filePath",required = false) String path,HttpServletRequest request, HttpServletResponse response){

        //设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="+ UUID.randomUUID().toString()+".txt");
        try {
//            URL url = new URL(path);
//            InputStream is = url.openStream();
            File targetFile = new File("/Users/lidong/gitHome/work/ld-study/结果.txt");
            //打开文件流
            InputStream is = new FileInputStream(targetFile);
//            InputStreamReader reader = new InputStreamReader(is);
            //打开输出流
            OutputStream os = response.getOutputStream();
            //开始下载，每次读取2048byte
            byte[] b = new byte[2048];
            int length = 0;
            while ((length = is.read(b))>0){
                os.write(b,0,length);
            }
            os.flush();
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
